import { generateDataInterface } from '@/types/modules/editor/server/code-transformer/utils/export/generateTsType';
import { ITypeEntity, ITypeEntityField } from '@/types/modules/superType/types';
import { getTypePath } from '../../utils/source-path';
import { parse } from '@babel/parser';
import * as t from '@babel/types';
import { parseTsType } from '@/types/modules/editor/server/code-transformer/utils/export/parseTsType';
import generate from '@babel/generator';

/**
 * 生成 API 类型实体的元数据注释 (JSDoc 格式)
 */
function generateApiTypeEntityMetaComment(typeEntity: ITypeEntity): string {
  const lines = [`/**`];

  // 主描述
  if (typeEntity.desc) {
    lines.push(` * ${typeEntity.desc}`);
  }

  // 详细介绍
  if (typeEntity.intro) {
    lines.push(` * ${typeEntity.intro}`);
  }

  // 只有当有描述时，才在描述和 API 信息之间添加空行分隔
  const hasDescription = typeEntity.desc || typeEntity.intro;
  if (hasDescription && typeEntity.uri) {
    lines.push(` *`);
  }

  // API 基本信息（保留这个，因为对 API 文件很重要）
  if (typeEntity.uri) {
    lines.push(
      ` * @api ${typeEntity.method?.toUpperCase() || 'GET'} ${typeEntity.uri}`,
    );
  }

  lines.push(` */`);
  return lines.join('\n');
}

export const apiTypeEntityToCode = async function (typeEntity: ITypeEntity) {
  const apiName =
    pathToPascalCase(typeEntity.uri) +
    typeEntity.method.charAt(0).toUpperCase() +
    typeEntity.method.slice(1).toLowerCase();
  let bodyDtoCode = '';
  const allImportTypeEntities: ITypeEntity[] = [];
  // const bodyParamsRootField = typeEntity.params.find((_) => _.name === '_root_');
  //   if (bodyParamsRootField?.import) {
  //     const importTypeEntities = await typeStore.fetchData({
  //       _id: bodyParamsRootField.import,
  //     });
  //     bodyDtoCode = `
  // /**
  //  * Body 参数类型
  //  */
  // export type ${apiName}BodyDto = ${importTypeEntities[0]?.name};\n`;
  //   } else {
  const { code: _bodyDtoCode, importTypeEntities } =
    await generateDataInterface(
      {
        type: 'vo',
        name: `${apiName}BodyDto`,
        desc: 'Body 参数类型',
        // fields: bodyParamsRootField?.fields || typeEntity.params,
        fields: typeEntity.params,
      },
      {
        isFileCode: true,
        hasDefaultValue: true,
        exportImportNames: true,
      },
    );
  bodyDtoCode = _bodyDtoCode;
  allImportTypeEntities.push(...importTypeEntities);
  // }
  const { code: queryDtoCode, importTypeEntities: queryImportTypeEntities } =
    await generateDataInterface(
      {
        type: 'vo',
        name: `${apiName}QueryDto`,
        desc: 'Query 参数类型',
        fields: typeEntity.query,
      },
      {
        isFileCode: true,
        hasDefaultValue: true,
        exportImportNames: true,
      },
    );
  allImportTypeEntities.push(...queryImportTypeEntities);
  const { code: pathDtoCode, importTypeEntities: pathImportTypeEntities } =
    await generateDataInterface(
      {
        type: 'vo',
        name: `${apiName}PathDto`,
        desc: 'Path 参数类型',
        fields: typeEntity.pathParams,
      },
      {
        isFileCode: true,
        hasDefaultValue: true,
        exportImportNames: true,
      },
    );
  allImportTypeEntities.push(...pathImportTypeEntities);

  const responseRootField = typeEntity.params.find((_) => _.name === '_root_');
  const {
    code: responseDtoCode,
    importTypeEntities: responseImportTypeEntities,
  } = await generateDataInterface(
    {
      type: 'vo',
      name: `${apiName}ResponseDto`,
      desc: '接口返回值类型',
      fields: typeEntity.fields,
    },
    {
      isFileCode: true,
      hasDefaultValue: true,
      exportImportNames: true,
    },
  );
  allImportTypeEntities.push(...responseImportTypeEntities);
  // 去重处理，按 _id 去重
  const uniqueImportTypeEntities = Array.from(
    new Map(
      allImportTypeEntities
        .filter(Boolean)
        .map((entity) => [entity._id, entity]),
    ).values(),
  );
  const importCode = uniqueImportTypeEntities
    .map(
      (entity) =>
        `import { ${entity.name} } from '@${getTypePath(entity).slice(
          0,
          -3,
        )}';`,
    )
    .join('\n');
  // 生成丰富的 JSDoc 元数据注释
  const apiDocComment = generateApiTypeEntityMetaComment(typeEntity);

  return `${apiDocComment}\n${importCode}
${[bodyDtoCode, queryDtoCode, pathDtoCode, responseDtoCode].join('\n')}`;
};

/**
 * 将路径 /aaa/bbb/ccc 转换为 AaaBbbCcc
 * @param path 路径字符串
 * @returns 驼峰式命名
 */
export function pathToPascalCase(path: string): string {
  return path
    .replace(/^\//, '') // 去掉开头的斜杠
    .split('/') // 按斜杠分割
    .map((str) =>
      // 只保留字母，并将每一段的首字母大写
      str
        .replace(/[^a-zA-Z]/g, '') // 去除非字母字符
        .replace(/^([a-zA-Z])/, (_, c) => c.toUpperCase()),
    )
    .join('');
}

// 用按行的括号计数法+export class定位，提取所有完整class片段
function extractAllClassesByExportLine(code: string): string[] {
  const lines = code.split('\n');
  const classes: string[] = [];
  let collecting = false;
  let braceCount = 0;
  let currentClass = [];
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    if (!collecting && line.includes('export class')) {
      collecting = true;
      braceCount = 0;
      currentClass = [];
    }
    if (collecting) {
      currentClass.push(line);
      if (line.includes('{')) braceCount += (line.match(/{/g) || []).length;
      if (line.includes('}')) braceCount -= (line.match(/}/g) || []).length;
      if (braceCount === 0 && currentClass.length > 0) {
        classes.push(currentClass.join('\n'));
        collecting = false;
        currentClass = [];
      }
    }
  }
  return classes;
}

export async function codeToApiTypeEntity(code: string): Promise<ITypeEntity> {
  // 兼容 class 声明后多余分号
  let codeStr = code.replace(/};/g, '}');
  console.log('[codeToApiTypeEntity] codeStr input:', codeStr);
  // 去掉 import 语句
  codeStr = codeStr.replace(/^import .*;$/gm, '');

  // 1. 解析顶部注释
  const commentMatch = codeStr.match(/\/\*\*([\s\S]*?)\*\//);
  let desc = '',
    uri = '',
    method = '',
    intro = '';
  if (commentMatch) {
    const comment = commentMatch[1];

    // 支持两种注释格式
    // 格式1: 接口名称: xxx, URI: xxx, Method: xxx, 说明: xxx
    desc = (comment.match(/接口名称: (.*)/) || [])[1] || '';
    uri = (comment.match(/URI: (.*)/) || [])[1] || '';
    method = (comment.match(/Method: (.*)/) || [])[1] || '';
    intro = (comment.match(/说明: (.*)/) || [])[1] || '';

    // 格式2: @api METHOD /path/to/api
    if (!uri || !method) {
      const apiMatch = comment.match(/@api\s+(\w+)\s+([^\s\n]+)/);
      if (apiMatch) {
        method = apiMatch[1].toLowerCase();
        uri = apiMatch[2];
      }
    }

    // 如果没有明确的描述，尝试提取第一行非空内容作为描述
    if (!desc) {
      const lines = comment
        .split('\n')
        .map((line) => line.replace(/^\s*\*\s?/, '').trim())
        .filter((line) => line && !line.startsWith('@'));
      if (lines.length > 0) {
        desc = lines[0];
      }
    }
  }
  console.log('[codeToApiTypeEntity] 注释解析', { desc, uri, method, intro });

  // 2. 用 AST 定位所有 class 节点，并连带前面的注释一起截取代码片段
  const ast = parse(codeStr, {
    sourceType: 'module',
    plugins: ['typescript', 'decorators-legacy'],
  });
  console.log(
    '[codeToApiTypeEntity] ast.program.body:',
    JSON.stringify(ast.program.body, null, 2),
  );
  const classSplits: string[] = [];
  (ast.program.body as any[]).forEach((node) => {
    if (
      node.type === 'ExportNamedDeclaration' &&
      node.declaration &&
      node.declaration.type === 'ClassDeclaration'
    ) {
      let start = node.start!;
      // 合并注释
      if (node.leadingComments && node.leadingComments.length > 0) {
        start = node.leadingComments[0].start!;
      }
      const end = node.end!;
      classSplits.push(codeStr.slice(start, end));
    }
  });
  console.log(
    '[codeToApiTypeEntity] classSplits:',
    classSplits.map((c, i) => `[${i}]:` + JSON.stringify(c)),
  );

  // 3. 解析每个 class，按命名规则归类
  const classFieldMap: Record<string, ITypeEntityField[]> = {};
  for (const cls of classSplits) {
    console.log(
      '[codeToApiTypeEntity] parseTsType input:',
      JSON.stringify(cls),
    );
    const typeEntity = (await parseTsType(cls, 'object')) as ITypeEntity;
    console.log('[codeToApiTypeEntity] parseTsType result:', {
      name: typeEntity?.name,
      fieldsCount: typeEntity?.fields?.length || 0,
      fields:
        typeEntity?.fields?.map((f) => ({ name: f.name, type: f.type })) || [],
    });
    if (!typeEntity || !typeEntity.name) continue;
    classFieldMap[typeEntity.name] = typeEntity.fields || [];
  }
  console.log(
    '[codeToApiTypeEntity] classFieldMap keys:',
    Object.keys(classFieldMap),
  );
  console.log(
    '[codeToApiTypeEntity] classFieldMap content:',
    Object.entries(classFieldMap).map(([key, fields]) => ({
      className: key,
      fieldsCount: fields.length,
      fields: fields.map((f) => ({ name: f.name, type: f.type })),
    })),
  );

  // 4. 命名规则
  function pathToPascalCase(path: string): string {
    return path
      .replace(/^\//, '')
      .split('/')
      .map((str) =>
        str
          .replace(/[^a-zA-Z]/g, '')
          .replace(/^([a-zA-Z])/, (_, c) => c.toUpperCase()),
      )
      .join('');
  }
  const apiName =
    pathToPascalCase(uri) +
    (method.charAt(0).toUpperCase() + method.slice(1).toLowerCase());
  console.log('[codeToApiTypeEntity] 计算的 apiName:', apiName);
  console.log('[codeToApiTypeEntity] 期望的类名:', {
    body: `${apiName}BodyDto`,
    query: `${apiName}QueryDto`,
    path: `${apiName}PathDto`,
    response: `${apiName}ResponseDto`,
  });
  console.log('[codeToApiTypeEntity] 实际的类名:', Object.keys(classFieldMap));

  const params = classFieldMap[`${apiName}BodyDto`] || [];
  const query = classFieldMap[`${apiName}QueryDto`] || [];
  const pathParams = classFieldMap[`${apiName}PathDto`] || [];
  const fields = classFieldMap[`${apiName}ResponseDto`] || [];

  console.log('[codeToApiTypeEntity] result', {
    params,
    query,
    pathParams,
    fields,
  });
  // 5. 组装 ITypeEntity
  const typeEntity: ITypeEntity = {
    name: apiName,
    desc,
    intro,
    type: 'api',
    uri,
    method,
    params,
    query,
    pathParams,
    fields,
  };
  return typeEntity;
}
